let baseUrl = 'https://owner.aezoo.com'

export const $url = baseUrl
export const $imgUrl = 'http://rpmis.aezoo.com' //图片地址
export const $shopImgUrl = 'http://shop.aezoo.com' //图片地址


// 方式请求
export function request(method, url, data = {}, header = {}) {
	return new Promise((resolve, reject) => {
		data.JSESSIONID = uni.getStorageSync('sessionid') || ''
		// if (token) {
		header = {
			...header,
			// 'Authorization': 'Bearer ' + token,
			'content-type':'application/x-www-form-urlencoded'
		}
		// }
		uni.request({
			url: baseUrl + url,
			method: method,
			data: data,
			dataType: 'json',
			header: header,
			success: (res) => {
				const {
					data,
					code,
					message
				} = res.data
				uni.stopPullDownRefresh()
				if (code==200) {
					resolve(data);
				} else if(code==999){
					uni.showToast({
						title:'请重新登录',
						icon:'none'
					})
					uni.reLaunch({
						url:'/pages/login/login'
					})
				} else if(code==205){
					uni.showToast({
						title:'请登陆后使用',
						icon:'none'
					})
				} else {
					uni.showToast({
						title:message,
						icon:'none'
					})
				}
			},
			fail: (error) => {
				if(error.errMsg=='request:fail abort statusCode:-1 Unable to resolve host \"owner.aezoo.com\": No address associated with hostname'){
					uni.showToast({
						title:'网络链接失败，请稍后再试',
						icon:'none'
					})
				}
				uni.stopPullDownRefresh()
				reject(error)
			}
		});
	})
}

let loginTime = 0;

function sleep(ms) {
	return new Promise((resolve) => setTimeout(resolve, ms));
}

async function again(method, url, data = {}) {
	await sleep(1000);
	var token = getApp().globalData.token || uni.getStorageSync('token')
	if (!token) {
		window.location.reload();
		return;
	}
	try {
		// 防止并发登录，造成性能浪费
		// const curTime = new Date().getTime();
		// if (curTime - loginTime > 5000) {
		// 	loginTime = curTime;
		// 	setTimeout(() => {
		// 		loginTime = 0
		// 	}, 5000);
		return await request(method, url, data)
		// } else {
		// 	await sleep(1000);
		// 	return
		// }
	} catch (e) {
		throw e;
	}
}


//上传图片
export function upload(url, imageSrc) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			filePath: imageSrc,
			fileType: 'image',
			name: 'file',
			success: (res) => {
				res = JSON.parse(res.data);
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}
